<?php

/**
 *  Component: JUser - Extends Jomla registration
 *  Author: http://joomlaequipment.com
 *  license: commercial http://joomlaequipment.com/content/view/10/42/
 *  version: 1.0.6
 */

// no direct access
defined( '_VALID_MOS' ) or die( 'Access Debied' );

function JUserDinList($fields_by_cat, $additional, $current_catid , $current_ordering){
  $JS .= '<script language="javascript">';
  $JS .= 'function catChange(catid){';
  foreach($fields_by_cat as $key => $cat){
    unset($options);
    $options[] = mosHTML::makeOption( 0, 'On the top');
    foreach($cat as $field){
     $options[] = mosHTML::makeOption( $field[ordering], $field[ordering].'.'.$field[title]);
    }
  	print mosHTML::selectList( $options, 'ordering', ' id="ordering_'.$key.'" '.($current_catid != $key ? 'disabled = "disabled" style="display:none"' : ''), 'value', 'text', $current_ordering );
  	//$JS .= 'alert(catid);';
    $JS .= 'if(catid == '.$key.'){';
  	$JS .= 'document.getElementById("ordering_'.$key.'").disabled = false;';
  	$JS .= 'document.getElementById("ordering_'.$key.'").style.display = "inline";';
  	$JS .= '}';
  	$JS .= 'else{';
  	$JS .= 'document.getElementById("ordering_'.$key.'").disabled = true;';
  	$JS .= 'document.getElementById("ordering_'.$key.'").style.display = "none";';
  	$JS .= '}';
  }
  $JS .= '}';
  $JS .= '</script>';
  print $JS;
  //document.getElementById("ordering_"+document.getElementById("select_cat_id").value)
}

function str_limit($str, $limit)
{
	if($str && strlen($str)>$limit){
		return substr($str,0,$limit-3).'...';
	}
	else{
		return $str;
	}
}

function RandString($aLen, $char_set = 'letterrs and numerals') {
	$d='';
	for($i=0; $i < $aLen; ++$i) {
	 if( (rand(0,9) < 6  || $char_set == 'numerals only') && $char_set != 'letters only' )
   {
     $d .= chr( ord('1') + rand(0,8) );
   }
	 else {
     do { $offset = rand(0,25);} while ( $offset==14 );
		 $d .= chr( ord('a') + $offset );
	 }
	}
	return $d;
}

function queryWithFlters($existing_where='', $total = false)
{
  global $database, $mainframe, $my, $acl;

  $result = '';

  //take list of field for filtering
  $database->setQuery("SELECT * FROM `#__extending_field_list` WHERE `search_by_this_field` = 1 AND `published` = 1");
  $fields = $database->loadObjectList();

  $additional_where = $existing_where;

  if($mainframe->isAdmin()){
    $option = 'com_juser';
    $filter_logged	= intval( $mainframe->getUserStateFromRequest( "filter_logged{$option}", 'filter_logged', 0 ) );
    $search 		= $mainframe->getUserStateFromRequest( "search{$option}", 'search', '' );
    $filter_type	= $mainframe->getUserStateFromRequest( "filter_type{$option}", 'filter_type', 0 );
  }
  else{
    $filter_logged	= mosGetParam($_REQUEST, 'filter_logged', 0 );
    $search 		= mosGetParam($_REQUEST, 'search', '' );
    $filter_type =  mosGetParam($_REQUEST,'filter_type',0);
    if ( $filter_type ) {
				$additional_where .= " AND a.gid = ".$filter_type." ";
  	}
  }
  $query = "SELECT ".($total ? "count(a.id)" : "a.*, g.name AS groupname")
  	. "\n FROM #__users AS a"
  	. "\n INNER JOIN #__core_acl_aro AS aro ON aro.value = a.id"	// map user to aro
	 . "\n INNER JOIN #__core_acl_groups_aro_map AS gm ON gm.aro_id = aro.aro_id"	// map aro to group
	 . "\n INNER JOIN #__core_acl_aro_groups AS g ON g.group_id = gm.group_id"
	 .($filter_logged == 1 ?  "\n INNER JOIN #__session AS s ON s.userid = a.id" : "")
	;

	if (get_magic_quotes_gpc()) {
		$filter_type	= stripslashes( $filter_type );
		$search			= stripslashes( $search );
	}
	if($mainframe->isAdmin()){
    if (isset( $search ) && $search!= ""){
      $search_word = $database->getEscaped( trim( strtolower( $search ) ) );
      $search_where = " AND (a.username LIKE '%$search_word%' OR a.email LIKE '%$search_word%' OR a.name LIKE '%$search_word%'";
    }
	}
	else{
	  if (isset( $search ) && $search!= ""){
      $search_word = $database->getEscaped( trim( strtolower( $search ) ) );
      $search_where = " AND (a.username LIKE '%$search_word%'"
      .( JEConfig::get('general.show_name_at_userlist')==1 ? " OR a.name like '%".$search_word."%'" : '')
      .( JEConfig::get('general.show_email_at_userlist')==1 ? " OR a.email like '%".$search_word."%'" : '');
    }
	}
	if(is_array($fields) && count($fields)>0){
    foreach($fields as $field)
    {
      if(mosGetParam($_REQUEST, $field->id.'filter_field') || ($search_word && ($field->type=='text' || $field->type=='textarea'))){
        $query .= "\n LEFT JOIN #__extending_field_list AS fl".$field->id." ON fl".$field->id.".id = ".$field->id;
        $query .= "\n LEFT JOIN #__users_extended_data AS add".$field->id." ON add".$field->id.".field_id = fl".$field->id.".id AND add".$field->id.".user_id = a.id";
        if($field->type == 'select' || $field->type == 'radio' || $field->type == 'checkbox'){
          $additional_where .= " AND add".$field->id.".uvalue = '".mosGetParam($_REQUEST, $field->id.'filter_field')."'";
        } else if ($field->type == 'date') {
		  $signs = array('=','>','<','>=','<=');

		  $filter_value	= mosGetParam($_REQUEST, $field->id.'filter_field', '' );
	      $filter_sign	= mosGetParam($_REQUEST, $field->id.'filter_field_sign', '' );
		  
		  $additional_where .= " AND add".$field->id.".uvalue ".$signs[$filter_sign+1]." '".$filter_value."'";
		} else{
          $search_where .= ($search_where ? " OR add".$field->id.".uvalue LIKE '%".$search_word ."%'" :"");
        }
      }
    }
  }

  $query .= " WHERE 1 \n ".$additional_where . $search_where.($search_where ? ')' : '');
  $query .= ($total ? "" : "\n GROUP BY a.id");
  //print str_replace('#__','jos_',$query).'<br>';
  
  return $query;
}

function require_integration($integration_id = 0)
{
  global $database, $mosConfig_absolute_path;
  if($integration_id == 0){
    $integration_id = mosGetParam($_REQUEST,'id','');
  }
  $database->setQuery("SELECT * FROM `#__juser_integration` WHERE `id` = ".$integration_id);
  $database->loadObject($component);

  $integration_com_id = $integration_id;
  require_once( $mosConfig_absolute_path.'/administrator/components/com_juser/integration/'.$component->component.'/'.$component->component.'.php' );

  return $synchronize;
}

function aletrnative_query ($first, $second)
{
  global $database;
  $database->setQuery($first);
  $database->query();
  if($database->getAffectedRows()<=0){
    $database->setQuery($second);
    $database->query();
  }
  return $database->getAffectedRows();
}

class InstallerIntegrationPlugin extends mosInstaller {
	/**
	* Custom install method
	* @param boolean True if installing from directory
	*/
	function install( $p_fromdir = null ) {
		global $mosConfig_absolute_path, $database;

		if (!$this->preInstallCheck( $p_fromdir, 'integration_plugin' )) {
			return false;
		}
		$xmlDoc 	= $this->xmlDoc();
		$mosinstall =& $xmlDoc->documentElement;

		$client = '';
		if ($mosinstall->getAttribute( 'client' )) {
			$validClients = array( 'administrator' );
			if (!in_array( $mosinstall->getAttribute( 'client' ), $validClients )) {
				$this->setError( 1, 'Unknown client type ['.$mosinstall->getAttribute( 'client' ).']' );
				return false;
			}
			$client = 'admin';
		}


		// Set some vars
		$e = &$mosinstall->getElementsByPath( 'name', 1 );
		$this->elementName($e->getText());
		$this->elementDir( mosPathName( $mosConfig_absolute_path
  		.'/administrator/components/com_juser/integration/'
  		.$this->elementName())
		);
		mosMakePath(mosPathName( $mosConfig_absolute_path
  		.'/administrator/components/com_juser/integration/'
  		.$this->elementName()));
		if ($this->parseFiles( 'files' ) === false) {
			return false;
		}
		$this->parseFiles( 'images' );
//id 	component 	published 	export_status 	import_status 	integration_data
		$client_id = intval( $client == 'admin' );
		// Insert in module in DB
		$query = "SELECT id FROM #__juser_integration"
		. "\n WHERE `component` = '".$this->elementName()."'"
		;
		$database->setQuery( $query );
		if (!$database->query()) {
			$this->setError( 1, 'SQL error: ' . $database->stderr( true ) );
			return false;
		}

		$id = $database->loadResult();

		if (!$id) {
  			$query = "INSERT INTO #__juser_integration (`component`, `integration_data`)"
  			. "\n VALUES ( '".$this->elementName()."', NOW() )"
  			;
  			$database->setQuery( $query );
  			if(!$database->query()) {
  				$this->setError( 1, 'SQL error: ' . $database->stderr( true ) );
  				return false;
  			}
  		}
  	else {
  		$this->setError( 1, 'Integration plugin "' . $this->elementName() . '" already exists!' );
  		return false;
  	}
		if ($e = &$mosinstall->getElementsByPath( 'description', 1 )) {
			$this->setError( 0, $this->elementName() . '<p>' . $e->getText() . '</p>' );
		}
 		return $this->copySetupFile('front');
  }

	function uninstall( $cid ) {
		global $database,$mosConfig_absolute_path;

		$uninstallret = '';

		$sql = "SELECT *"
		. "\n FROM #__juser_integration"
		. "\n WHERE id = $cid"
		;
		$database->setQuery($sql);

		$row = null;
		if (!$database->loadObject( $row )) {
		  $this->setError( 1, 'SQL error: ' . $database->stderr( true ) );
			return false;
		}

		// Delete entries in the DB
		$sql = "DELETE FROM #__juser_integration"
		. "\n WHERE id = $row->id"
		;
		$database->setQuery($sql);
		if (!$database->query()) {
			$this->setError( 1, 'SQL error: ' . $database->stderr( true ) );
			return false;
		}
		$sql = "DELETE FROM #__juser_integration_comparisons"
		. "\n WHERE `component_id` = $row->id"
		;
		$database->setQuery($sql);
		if (!$database->query()) {
			$this->setError( 1, 'SQL error: ' . $database->stderr( true ) );
			return false;
		}

		// Delete directories

		$result = false;
		$path = mosPathName( $mosConfig_absolute_path.'/administrator/components/com_juser/integration/'.$row->component );
		if (is_dir( $path )) {
			$result |= deldir( $path );
		}
		return $result;
	}
}

 class exteriorFieldType
 {
   var $type        = '';
   var $system      = false;
   var $comparisons = array();
   var $default     = '';
 }

 class synchronizeUsersData
 {
   var $com_name          = '';
   var $com_id            = '';
   var $com_published     = '';
   var $com_export_status = '';
   var $field_list        = array();
   var $suggestions       = array();
   var $types_properties  = array();
   var $timestart         = 0;
   var $timeend           = 0;
   var $timesumm          = 0;
   function synchronizeUsersData($component_id)
   {
     global $database, $mosConfig_absolute_path;
     $database->setQuery("SELECT * FROM `#__juser_integration` WHERE `id` = ".$component_id);
     $database->loadObject($component);

     $this->com_name          = $component->component;
     $this->com_published     = $component->published;
     $this->com_export_status = $component->export_status;
     $this->com_id            = $component->id;
     $field_struct = $this->getFieldStruct();
     $this->field_list        = $field_struct['fields'];
     $this->suggestions       = $field_struct['suggestions'];
     $this->types_properties  = $this->getTypesProperties();
   }
   function startT()
   {
     $this->timestart = explode(' ',microtime());
     $this->timestart =  $this->timestart[0] + $this->timestart[1];
   }
   function endT()
   {
     $lastTimeEnd     = $this->timeend;
     $this->timeend   = explode(' ',microtime());
     $this->timeend   = $this->timeend[0]+$this->timeend[1];
     $this->timesumm  += ($this->timeend - $this->timestart);
   }
   function getExteriorUserList($integration_limit_start = 0)
   {
     die( 'Method "getExteriorUserList" cannot be called by class ' . strtolower(get_class( $this )) );
   }
   function getFieldStruct()
   {
     die( 'Method "getFieldStruct" cannot be called by class ' . strtolower(get_class( $this )) );
   }
   function getTypesProperties()
   {
     die( 'Method "getFieldList" cannot be called by class ' . strtolower(get_class( $this )) );
   }
   function deleteExteriorUser($user_id)
   {
     die( 'Method "deleteExteriorUser" cannot be called by class ' . strtolower(get_class( $this )) );
   }
   function createNewExteriorUser( $exteriorUserId = '' )
   {
     die( 'Method "createNewExteriorUser" cannot be called by class ' . strtolower(get_class( $this )) );
   }
   function clean_exterior()
   {
     die( 'Method "clean_exterior" cannot be called by class ' . strtolower(get_class( $this )) );
   }
   function convertionFrom($type, $exteriorUserId='', $juserUserId='', $field_name='', $value='', $juserFieldId='')
   {
     die( 'Method "convertionFrom" cannot be called by class ' . strtolower(get_class( $this )) );
   }
   function convertionIn($type, $exteriorUserId='', $juserUserId='', $field_name='', $value='', $juserFieldId='')
   {
     die( 'Method "convertionIn" cannot be called by class ' . strtolower(get_class( $this )) );
   }

   function getConfrontation($ident, $juserFieldId, $convertion_type = 'export')
   {
      global $database;
      $result = array();
      $suggestions = $this->suggestions[$ident];
      $database->setQuery("SELECT `type` FROM `#__extending_field_list` WHERE `id` = ".$juserFieldId);
      $juserType = $database->loadResult();
      foreach($suggestions as $suggestion){
        if( $suggestion['type'] == $juserType && is_array($suggestion['values']) ){
          unset($result);
          if(is_array($suggestion['conform'])){
            foreach($suggestion['values'] as $key => $value){
              //print '$suggestion:<pre>';print_r($suggestion);print'</pre>';exit;
              if($convertion_type == 'export'){
                $result[$value] = $suggestion['conform'][$key];
              }
              else if($convertion_type == 'import'){
                $result[$suggestion['conform'][$key]] = $value;
              }
            }
          }
        }
      }
      return $result;
   }
   function getFieldByAttribute( $attribute, $value, $mode = 'single' )
   {
     foreach($this->field_list as $field){
       if($field[$attribute] == $value){
         if($mode == 'single'){
           return $field;
         }
         else if($mode == 'array'){
           $result[] = $field;
         }
       }
     }
     return $result;
   }
   function getComparisonFields($types)
   {
      $comparisonFields=array();
      global $database;
      if(is_array($types) && count($types)>0){
         $database->setQuery("SELECT `id`, `title`, `type`"
                             ."\n FROM #__extending_field_list"
                             ."\n WHERE `type` IN('".implode("','",$types)."')");
         $comparisonFields=$database->loadObjectList();
      }
      return $comparisonFields;
   }

   function is_integrationReady( $mode='export' )
   {
     global $database;
     $field_list=$this->field_list;
     if( !is_array($field_list) || count($field_list)<=0 ) return false;

     foreach($field_list as $field){
       $query="SELECT `juser_field_id`, `integrate`, `static_juser_field` FROM `#__juser_integration_comparisons` WHERE `component_id` = ".$this->com_id." AND `ident` = '".$field['ident']."'";
       $database->setQuery($query);
       $database->loadObject($row);
       if( $row->juser_field_id <= 0 && !$row->static_juser_field ){
         if(!$this->types_properties[$field['type']]->system && ($row->integrate == 'required' || $row->integrate == 'integrate' ))return false;
       }
       else if( $row->juser_field_id == 0  && !$row->static_juser_field && $row->integrate != 'system' ){
         return false;
       }
     }
     return true;
   }

   function updateExteriorUser($user_id)
   {
     $this->deleteExteriorUser($user_id);
     $this->synchronizeFrom($user_id);
   }

   function synchronizeFrom($user_id)
   {
     global $database;
     $this->startT();

     $juser_users[0] = $user_id;

     $query = "SELECT * FROM `#__juser_integration_comparisons`"
              ."\n WHERE `component_id` = ".$this->com_id;
     $database->setQuery($query);
     $comparisons = $database->loadObjectList();

     $newUserId=1;
     foreach($juser_users as $juser_user)
     {
        $this->createNewExteriorUser( $juser_user );
        foreach($comparisons as $comparison){

          if($comparison->integrate <= '0') continue;

          $exterior_field = $this->getFieldByAttribute('ident', $comparison->ident);

          if( $comparison->integrate != 'system' ){
            if( $comparison->juser_field_id > 0 ){
              $database->setQuery("SELECT `uvalue` FROM `#__users_extended_data` WHERE `user_id` = ".$juser_user." AND `field_id` = ".$comparison->juser_field_id);
              $juserValue = $database->loadResult();
              /*if($exterior_field['type'] == 'select'){
                print "SELECT `uvalue` FROM `#__users_extended_data` WHERE `user_id` = ".$juser_user." AND `field_id` = ".$comparison->juser_field_id;
                print'<br>$juserValue:'.$juserValue.'<br>';
              }*/
              $confrontation = $this->getConfrontation( $comparison->ident, $comparison->juser_field_id );
              if(count($confrontation)>0){
                if($juserValue){
                  $juserValue = $confrontation[$juserValue];
                }
                else{
                  $juserValue = $confrontation[$comparison->default_value];
                }
              }
              else{
                if(!$juserValue) $juserValue = $comparison->default_value;
              }
            }
            else if( $comparison->static_juser_field  ){
              $juserValue = '';
            }
          }
          $this->convertionFrom( $exterior_field['type'], $newUserId, $juser_user, $comparison->name, $juserValue );
        }
        $newUserId++;
     }
     $this->endT();
   }
   function synchronizeIn($user_id = null)
   {
     global $database;
     $this->startT();

     $exteriorUserList[0] = $user_id;

     $query = "SELECT * FROM `#__juser_integration_comparisons`"
              ."\n WHERE `component_id` = ".$this->com_id;
     $database->setQuery($query);
     $comparisons = $database->loadObjectList();

     $newUserId=1;
     foreach($exteriorUserList as $exterior_user)
     {
        foreach($comparisons as $comparison){
          if( $comparison->integrate == 'system' ) continue; // if integrate of current field is system then go to next field
                                                             // (because) system field cant have $comparisons in JUser
          if($comparison->integrate <= '0')        continue; // if integrate of current field is not active then go to next field
          if($comparison->juser_field_id <= '0')   continue; // if JUser don`t have comparison with exterior compomponent field then go to next field

          $exterior_field = $this->getFieldByAttribute('ident', $comparison->ident);

          $exteriorValue = $this->convertionIn($exterior_field['type'], $exterior_user, $exterior_user, $comparison->name, '', $comparison->juser_field_id);  //take curent field value from exterior component

          $confrontation = $this->getConfrontation( $comparison->ident, $comparison->juser_field_id, 'import' );
          if(count($confrontation)>0){
            if($exteriorValue){
              $exteriorValue = $confrontation[$exteriorValue];
            }
            else{
              $exteriorValue =$comparison->default_value;
            }
          }
          else{
            if(!$exteriorValue) $exteriorValue = $comparison->default_value;
          }

          $query="DELETE FROM `#__users_extended_data` WHERE `user_id` = ".$exterior_user." AND `field_id` = ".$comparison->juser_field_id;
          $database->setQuery($query);
          $database->query();
      	  $query = "INSERT INTO `#__users_extended_data`"
                          	      ."\n (`user_id`, `field_id`, `uvalue`, `ctime`)"
                           ."\n VALUES ( ".$exterior_user.", '".$comparison->juser_field_id."', '".$exteriorValue."', NOW())";
          $database->setQuery($query);
          $database->query();
        }
        $newUserId++;
     }
     $this->endT();
   }
 }




 class mosJUser extends mosDBTable {

	/** @var int Primary key */
	var $id						= null;
	/** @var string */
	var $title					= null;
	/** @var int */
	var $published				= null;
	/** @var int */
	var $required				= null;
	/** @var string */
	var $validate				= null;
	/** @var string */
	var $type					= null;
	/** @var int */
	var $size					= null;
	/** @var string */
	var $size_vertical			= null;
	/** @var string */
	var $uvalues				= null;
	/** @var string */
	var $table_align			= null;
	/** @var int */
	var $changeable				= null;
	/** @var string */
	var $description			= null;
	/** @var string */
	var $valid_error_msg		= null;
	/** @var int */
	var $count_cols				= null;
	/** @var int */
	var $reg_only				= null;
	/** @var int */
	var $ordering				= null;
	/** @var int */
	var $alternative_value		= null;
	/** @var int */
	var $checked_out			= null;
	/** @var time */
	var $checked_out_time		= null;
	/** @var int */
	var $catid					= null;

	function mosJUser( &$db ) {
		$this->mosDBTable( '#__extending_field_list', 'id', $db );
	}
	// overloaded check function
	function check() {
		// check for valid name
		if (trim( $this->title ) == '') {
			$this->_error = "Your Field must contain a title.";
			return false;
		}

		return true;
	}
}

class mosUserParameters extends mosParameters {

	function _form_editor_list( $name, $value, &$node, $control_name ) {
		global $database;

		$query = "SELECT element AS value, name AS text"
		. "\n FROM #__mambots"
		. "\n WHERE folder = 'editors'"
		. "\n AND published = 1"
		. "\n ORDER BY ordering, name"
		;
		$database->setQuery( $query );
		$editors = $database->loadObjectList();

		array_unshift( $editors, mosHTML::makeOption( '', '- Select Editor -' ) );

		return mosHTML::selectList( $editors, ''. $control_name .'['. $name .']', 'class="inputbox"', 'value', 'text', $value );
	}
}

class JUser {
	function csvStringToArray($csv_string = "", $cell_separator=";", $row_separator="\n", $enclose='"', $encode_quote='""', $decode_quote='"')
	{
		if( !$csv_string ) return NULL;
		$result = explode( $row_separator, $csv_string );
		$i_row=0;
		if( count( $result ) > 0 )
		{
			foreach( $result as $row )
			{
				$result[$i_row] = explode( $cell_separator, $row );
				print_r($result[$i_row]);
				$i_cell=0;
				if( count( $result[$i_row] ) > 0 )
				{
					foreach($result[$i_row] as $cell)
					{
						$result[$i_row][$i_cell]= trim($cell);
						if(substr( trim($result[$i_row][$i_cell]), 0, 1 )==$enclose)
							$result[$i_row][$i_cell]=substr($result[$i_row][$i_cell],1,strlen($result[$i_row][$i_cell])-2);
						$result[$i_row][$i_cell]=str_replace( $encode_quote, $decode_quote, $result[$i_row][$i_cell] );
						$i_cell++;
					}
				}
				$i_row++;
			}
		}
		return $result;
	}
	function writableCell( $folder ) {
		echo '<tr>';
		echo '<td class="item">' . $folder . '/</td>';
		echo '<td align="left">';
		echo is_writable( $GLOBALS['mosConfig_absolute_path'] . '/' . $folder ) ? '<b><font color="green">Writeable</font></b>' : '<b><font color="red">Unwriteable</font></b>' . '</td>';
		echo '</tr>';
	}
	function SendNewsleter($message, $mode)
	{

    global $database, $mosConfig_absolute_path;
    
    //print $message; exit;
    
    $fields[] = mosGetParam($_REQUEST, 'condition_filed_1' );
    $fields[] = mosGetParam($_REQUEST, 'condition_filed_2' );
    $fields[] = mosGetParam($_REQUEST, 'condition_filed_3' );

    $sign[] = $_REQUEST['condition__sign_1'];
    $sign[] = $_REQUEST['condition__sign_2'];
    $sign[] = $_REQUEST['condition__sign_3'];

    $param[] = mosGetParam($_REQUEST, 'condition__sign_param1' );
    $param[] = mosGetParam($_REQUEST, 'condition__sign_param2' );
    $param[] = mosGetParam($_REQUEST, 'condition__sign_param3' );

    $subsc = mosGetParam($_REQUEST, 'condition_jcs', array(), 'array' );

		$sub_querys  = ",	(select `uvalue` from #__users_extended_data"
						."\n		where `field_id` = '".$fields[0]."' AND `user_id` = u.id) as field_".$fields[0]
						.",\n	(select `uvalue` from #__users_extended_data"
						."\n		where `field_id` = '".$fields[1]."' AND `user_id` = u.id) as field_".$fields[1]
						.",\n	(select `uvalue` from #__users_extended_data"
						."\n		where `field_id` = '".$fields[2]."' AND `user_id` = u.id) as field_".$fields[2];
		if(is_dir($mosConfig_absolute_path."/administrator/components/com_jcs")){
      $t=0;
      if(!$subsc[0]){$t++;}
			if((count($subsc)-$t)>0)
			{
				$where = " AND (select count(`id`) from `#__jcs_user_subscr` as `jcs`"
						."\n		where jcs.user_id = u.id AND jcs.subscription_id IN (";
				$pr=false;
				foreach($subsc as $jcs_condition)
				{
          if(!$jcs_condition) continue;
					$where .= $pr ? ',' : '';
					$where .= $jcs_condition;
					$pr = true;
				}
				$where .= ") ) > 0";
			}
		}

		$query = "SELECT u.* "
			."\n ".$sub_querys
			."\n FROM `#__users` AS u"
			."\n WHERE 1 ".$where
			."\n HAVING 1 "
			. ($param[0]?" AND field_".$fields[0]." ".$sign[0]." '".($sign[0]=='like'?'%'.$param[0].'%':$param[0])."'":"")
			. ($param[1]?" AND field_".$fields[1]." ".$sign[1]." '".($sign[1]=='like'?'%'.$param[1].'%':$param[1])."'":"")
			. ($param[2]?" AND field_".$fields[2]." ".$sign[2]." '".($sign[2]=='like'?'%'.$param[2].'%':$param[2])."'":"")
			;

		$database->setQuery( $query );
		$users = $database->loadObjectList();

    if(count($users)<=0) return 0;

		$query = "SELECT name, email"
		. "\n FROM #__users"
		. "\n WHERE LOWER( usertype ) = 'superadministrator'"
		. "\n OR LOWER( usertype ) = 'super administrator'"
		;
		$database->setQuery( $query );
		$admin_rows = $database->loadObjectList();
		$admin_rows2 			= $admin_rows[0];

		$adminName2 	= $admin_rows2->name;
		$adminEmail2 	= $admin_rows2->email;
		foreach($users as $user)
		{
		  
			mosMail( $adminEmail2, $adminName2, $user->email, mosGetParam($_REQUEST, 'subject' ), $message, $mode );
		}
		return count($users);
	}

	function justify_month($rows,$label_title="label",$value_title="value", $show_label=true,$first='?',$month_back=12)
	{
		$months=array('Jan'=>12,'Feb'=>11,'Mar'=>10,'Apr'=>9,'May'=>8,'Jun'=>7,'Jul'=>6,'Aug'=>5,'Sep'=>4,'Oct'=>3,'Nov'=>2,'Dec'=>1);
		$flip_months=array_flip($months);
		$current_month=$rows[0]->current_month;
		foreach($rows as $row){
			while($current_month != $row->month){
				$i++;
				$value[$i]=0;
				$label[$i]=$current_month;
				if($months[$current_month]+1 <=12){
					$current_month=$flip_months[($months[$current_month]+1)];
				}else{
					$current_month=$flip_months[1];
				}
			}
			$i++;
			$value[$i]=$row->colvo;
			$label[$i]=$row->month;
			if($months[$current_month]+1 <=12){
				$current_month=$flip_months[($months[$current_month]+1)];
			}else{
				$current_month=$flip_months[1];
			}
		}
		while($i < $month_back){
			$i++;
			$value[$i]=0;
			$label[$i]=$current_month;
			if($months[$current_month]+1 <=12){
				$current_month=$flip_months[($months[$current_month]+1)];
			}else{
				$current_month=$flip_months[1];
			}
		}
		$value=array_reverse($value);
		$label=array_reverse($label);
		if(count($value)>0){
			$result=$first.$value_title.'='.implode('|',$value);
			if($show_label){
				$result.='&'.$label_title.'='.implode('|',$label);
			}
		}
		return $result;
	}
	function justify_day($rows,$label_title="label",$value_title="value", $show_label=true,$first='?',$days=31)
	{
		$i=$days+1;
		foreach($rows as $row){
			while($i-1 != $row->day){
				$i--;
				$value[$i]=0;
				$label[$i]=$i;
			}
			$i--;
			$value[$i]=$row->colvo;
			$label[$i]=$row->day;
		}
		while($i!=1){
			$i--;
			$value[$i]=0;
			$label[$i]=$i;
		}
		$value=array_reverse($value);
		$label=array_reverse($label);
		if(count($value)>0){
			$result=$first.$value_title.'='.implode('|',$value);
			if($show_label){
				$result.='&'.$label_title.'='.implode('|',$label);
			}
		}
		return $result;
	}
	function make_table_data($label,$value,$title)
	{
	
		global $mosConfig_live_site;
		$data_table='<table cellpadding="4" cellspacing="1" border="0" class="adminform" width="620px" style="width:620px;">';
		$data_table.='<tr><th class="title" width="15px">#</th><th class="title" >Value</th><th class="title" width="65px">Count</th><th class="title" width="30px">%</th></tr>';
		$k=0;
		$i=0;
		$summ=array_sum($value);
		foreach($value as $val)
		{
			$data_table.=	'<tr class="row'.$k.'">'
					."\n".		'<td>'.($i+1).'</td><td>'.$label[$i].'</td><td>'.$val.'</td><td>'.round($val/($summ/100),2).'%</td>'
					."\n".	'</tr>';
			$k=1-$k;
			$i++;
		}
		$data_table.='</table><br><br>';
		if(mosgetparam($_POST,"task") != "report_for_print")
		{
			$url='?label='.urlencode(serialize($label));
			$url.='&value='.urlencode(serialize($value));
			$url.='&title='.$title;
			$data_table='<br><br>Download this Table as Microsoft &reg; Excel format <a style="border:none" href="'.$mosConfig_live_site.'/administrator/components/com_juser/table_data.php'.$url.'"><img align="absmiddle" style="border:none" src="'.$mosConfig_live_site.'/administrator/components/com_juser/img/xls.png"></a>'.$data_table;
		}
		return $data_table;
	}

	function make_graph($field)
	{
		global $database,$mosConfig_absolute_path,$mosConfig_live_site;

		if(mosgetparam($_POST,'from'))
		{
			$date_limit_from=" AND `registerDate` >= '".mosgetparam($_POST,'from')."' ";
		}
		if(mosgetparam($_POST,'to'))
		{
			$date_limit_to=" AND `registerDate` <= '".mosgetparam($_POST,'to')."' ";
		}

		switch($field->type)
		{
			case 'radio':
			case 'select':
				/*$query = "SELECT count(#__users_extended_data.id) as `colvo`, `uvalue`"
						. "\n FROM  `#__users_extended_data`,#__users"
						. "\n WHERE `field_id` = ".$field->field_id." AND #__users.id = user_id ".$date_limit_from." ".$date_limit_to
						. "\n GROUP BY `uvalue`"
						. "\n ORDER BY `colvo` desc";*/
				$query = "SELECT count(u.id) as `colvo`, `uvalue`"
							."\n FROM `#__users_extended_data` AS d"
							."\n LEFT JOIN `#__users` AS u ON u.id = d.user_id AND d.field_id = ".$field->field_id
							."\n WHERE 1 ".$date_limit_from." ".$date_limit_to
							."\n GROUP BY d.`uvalue`"
							."\n ORDER BY `colvo` DESC";
				$database->setQuery( $query );
				//echo $query;
				$rows = $database->loadObjectList();
				$i=0;
				//print_r($rows);
				if(!$rows)
				{
					echo "No Data found on <B>$field->title</B><BR>";
					return;
				}
				foreach($rows as $row)
				{
					$value[]=$row->colvo;
					if(is_null($row->uvalue)){
						$label[]='Field not created';
						$label_table[]='Field not created';
					}
					else if(!$row->uvalue)
					{
						$label[]='Not filled';
						$label_table[]='Not filled';
					}
					else{
						$label[]=strlen($row->uvalue)<=22?'('.$value[$i].')'.$row->uvalue:'('.$value[$i].')'.substr($row->uvalue,0,20).'...';
						$label_table[]=$row->uvalue;
					}
					$i++;
				}
				$url='?type_0=pie&value_0_0='.urlencode(serialize($value));
				$url.='&label_0_0='.urlencode(serialize($label));
				$url.='&title='.$field->title;
				$url.='&xsize=620';
				if(count($label)>20)
				{
					$url.=round(20*(60/3)+30)>=170?'&ysize='.round(20*(60/3)+30):'&ysize=170';
				}
				else
				{
					$url.=round(count($label)*(60/3)+30)>=170?'&ysize='.round(count($label)*(60/3)+30):'&ysize=170';
				}
				//print'<div align="left" style="color:#990099"><pre>';print str_replace("#_",'jos',$query);print'</pre></div>';
				print'<img src="'.$mosConfig_live_site.'/administrator/components/com_juser/multi_graph.php'.$url.'">';
				print JUser::make_table_data($label_table,$value,$field->title);
				break;
			case 'checkbox':
				/*$query = "SELECT `uvalue`"
						. "\n FROM  `#__users_extended_data`,#__users"
						. "\n WHERE `field_id` = ".$field->field_id." AND #__users.id = user_id ".$date_limit_from." ".$date_limit_to;*/
				$query = "SELECT `uvalue`"
						. "\n FROM  #__users"
						. "\n LEFT JOIN `#__users_extended_data` ON #__users.id = user_id AND `field_id` = ".$field->field_id
						. "\n WHERE 1 ".$date_limit_from." ".$date_limit_to;
				$database->setQuery( $query );
				$rows = $database->loadObjectList();

				if(count($rows)<=0)
				{
					echo "No Data found on <B>$field->title</B><BR>";
					return;
				}
				foreach($rows as $row){
					if(is_null($row->uvalue)){
						$pre_value[]='Field not created';
					}
					else{
						foreach(explode("\n",str_replace("\r",'',$row->uvalue))as $under_row){
							$pre_value[]=$under_row?$under_row:'Not filled';
						}
					}
				}
				if(count($pre_value) <= 0) return;
				foreach($pre_value as $under_row)
				{
					$out[$under_row]++;
				}
				natsort($out);
				$i=0;
				foreach($out AS $key => $val)
				{
					$label[(count($out)-$i-1)]  = $key;
					$value[(count($out)-$i-1)]  = $val;
					$i++;
				}
				ksort($label);
				ksort($value);

				$url='?type_0=pie&value_0_0='.urlencode(serialize($value));
				$url.='&label_0_0='.urlencode(serialize($label));
				$url.='&title='.$field->title;
				$url.='&xsize=620';
				$url.=round(count($label)*(50/3)+30)>=170?'&ysize='.round(count($label)*(50/3)+30):'&ysize=170';
				//print'<div align="left" style="color:#990099"><pre>';print str_replace("#_",'jos',$query);print'</pre></div>';
				print'<img src="'.$mosConfig_live_site.'/administrator/components/com_juser/multi_graph.php'.$url.'" alt="Graph">';
				print JUser::make_table_data($label,$value,$field->title);
				break;
		}
	}
	function report_execute()
	{
		global $database,$mosConfig_live_site;

		?><form action="index3.php" method="post" name="adminForm" TARGET="_blank"><?php
		/**Total for year**/
		if(mosgetparam($_POST, 'show_total')==1)

		{
		print'<div align="left"><h2>'.R_TABLE_FIELDS_TOTALSTATISIC.'</h2></div>';
			/**Total for last 2 month**/
			$query = "SELECT count( `id` ) AS `colvo` , DAYOFMONTH( `registerDate` ) AS `day`,MONTHNAME( `registerDate` ) as `month`"
					. "\n FROM #__users"
					. "\n WHERE MONTH( `registerDate` ) = MONTH( now( ) )"
					. "\n GROUP BY `day`"
					. "\n ORDER BY `day` desc";
			$database->setQuery( $query );
			$rows = $database->loadObjectList();
			$urlquery_totaltwomonth=JUser::justify_day($rows);
			$urlquery_totaltwomonth.='&value_plot_legend='.$rows[0]->month;
			$urlquery_totaltwomonth.='&title=Registration Progress For Last 2 Month';
			$query = "SELECT count( `id` ) AS `colvo` , DAYOFMONTH( `registerDate` ) AS `day` , `registerDate`, MONTHNAME( `registerDate` ) as `month`"
						."\n FROM #__users"
						."\n WHERE MONTH( `registerDate` ) = MONTH( now( ) - INTERVAL 1 MONTH )"
						."\n GROUP BY `day`"
						."\n ORDER BY `day` DESC ";
			$database->setQuery( $query );
			$rows = $database->loadObjectList();

			$urlquery_totaltwomonth.=JUser::justify_day($rows,'',"value_plot2", false,'&');
			$urlquery_totaltwomonth.='&sizex=900&value_plot2_legend='.$rows[0]->month;
			$urlquery_totaltwomonth.='&title=Registration Progress For Last 2 Month';
  		print '<div align="left" class="small">This graph shows Registration progress for last 30 days.</div>';
			print'<div align="left">';
			print'<img src="'.$mosConfig_live_site.'/administrator/components/com_juser/graph.php'.$urlquery_totaltwomonth.'">';
			print'</div>';

  	  print '<div align="left" class="small">This graph shows Registration progress for last Year monthly.</div>';
			$query = "SELECT count(`id`) as `colvo`, DATE_FORMAT(`registerDate`,'%b') as `month`,DATE_FORMAT(now(),'%b') as `current_month`"
				. "\n FROM #__users"
				. "\n WHERE `registerDate` >= (now() - INTERVAL 12 MONTH)"
				. "\n GROUP BY `month`"
				. "\n ORDER BY `registerDate` desc";
			$database->setQuery( $query );
			$rows = $database->loadObjectList();
			$urlquery_totalyear=JUser::justify_month($rows);
			$urlquery_totalyear.='&title=Registration Progress For Last 12 Month';

			$query = "SELECT count(`id`) as `colvo`,`block`, DATE_FORMAT(`registerDate`,'%b') as `month`,DATE_FORMAT(now(),'%b') as `current_month`"
				. "\n FROM #__users"
				. "\n WHERE `registerDate` >= (now() - INTERVAL 12 MONTH) AND `block` = 0"
				. "\n GROUP BY `month`"
				. "\n ORDER BY `registerDate` desc";
			$database->setQuery( $query );
			$rows = $database->loadObjectList();
			$urlquery_totalyear.=JUser::justify_month($rows,'','value_line',false,'&');
			$urlquery_totalyear.='&sizex=550';
			$urlquery_totalyear.='&value_plot_legend=Registered Users';
			$urlquery_totalyear.='&line_legend=Activated Users';
			print'<div align="left">';
			print'<img src="'.$mosConfig_live_site.'/administrator/components/com_juser/graph.php'.$urlquery_totalyear.'">';
			print'</div>';
			/**Total for year (end)**/
		}
		print'<div align="left"><h2 align="left">'.R_TABLE_FIELDS_STATISTICBYFIELDS.'</h2></div>';
			$get_fields=mosGetparam($_REQUEST, 'field', array(0), 'array');

      //print_r($get_fields);
      if($get_fields)
      {
          $ids = implode(",", $get_fields);
          $query = "SELECT #__extending_field_list. *, #__extending_field_list.id as `field_id`, #__categories.title as cat_title, #__categories.description as cat_description"
              . "\n FROM #__extending_field_list"
              . "\n LEFT JOIN #__categories ON #__categories.id = #__extending_field_list.catid"
              . "\n WHERE  #__extending_field_list.id IN ($ids) "
              . "\n ORDER by #__categories.ordering, #__extending_field_list.ordering";
          $database->setQuery( $query );
          $extended_fields = $database->loadObjectList();
          foreach($extended_fields as $field)
          {
              print'<div align="left">';
              //print'<pre>';print_r($field);print'</pre>';
              JUser::make_graph($field);
              print'</div>';
          }
          foreach($get_fields as $field)
          {
              ?><input type="hidden" name="field[]" value="<?php echo $field;?>" /><?php
          }
      }
			?>
        <input type="hidden" name="to" value="<?php echo mosgetparam($_POST,'to');?>" />
				<input type="hidden" name="from" value="<?php echo mosgetparam($_POST,'from');?>" />
				<input type="hidden" name="show_total" value="<?php echo mosgetparam($_POST,'show_total');?>" />
				<input type="hidden" name="option" value="com_juser" />
				<input type="hidden" name="task" value="" />
				<input type="hidden" name="hidemainmenu" value="0" />
			</form>
      <?php
		/**Total for last 2 month (end)**/

	}


	function validateSaveUser( $path, $side='admin',$task) //validate on $field->validate,$field->required,$field->unique
	{
		global $database, $my;
		$userIdPosted = mosGetParam($_POST, 'id');
		$query = "SELECT fl. *,"
               . "\n fl.id as `field_id`,"
               . "\n c.title as `cat_title`,"
               . "\n c.description as `cat_description`"
   			. "\n FROM #__extending_field_list as `fl`"
   			. "\n LEFT JOIN #__categories as `c` ON c.id = fl.catid"
   			. "\n ORDER BY c.ordering, fl.ordering";
		$database->setQuery( $query );
		$extended_fields = $database->loadObjectList();

    $is_siteUserEdit=(mosGetParam($_REQUEST, 'task')=='UserDetails' || mosGetParam($_REQUEST, 'task')=='saveUserEdit');

    $error=false;

    if(JEConfig::get('general.enable_avatar') == 1)
    {
      $ufile = $_FILES['field_core_avatar'];
      $ufile_properti=getimagesize($ufile['tmp_name']);
      $hidden_avatar = mosGetParam($_POST, 'field_core_avatar_hidden','');
			$value = $ufile['name'];
      if( !$value && !$hidden_avatar && JEConfig::get('general.required_avatar')==1)
			{

				$extended_fields['coreavatarerror']->errormsg = MSG_IF_FIELD_IS_EMPTY;
				$error = true;

			}
      /*else if($ufile_properti[0] > JEConfig::get('general.max_size') || $ufile_properti[1] > JEConfig::get('general.max_size'))
      {
      	//print_r($ufile_properti);
        $extended_fields['coreavatarerror']->errormsg = MSG_IF_FILE_IS_TOOBIG;
				$error = true;
      }*/
       if( $value && JEConfig::get('general.avatar_allowed_extends') )
			{
      $ex_val=true;

		$extentions= explode("\n",str_replace("\r",'',JEConfig::get('general.avatar_allowed_extends')));
   		foreach($extentions as $extend)
   		{
   			if(strtolower(str_replace('.','',strrchr($value,'.'))) == strtolower($extend))
   			{
   				$ex_val=false;
   			}
   		}
   		if($ex_val) $extended_fields['coreavatarerror']->errormsg = HEAD_MSG_IF_FILE_EXTEND_ISNOT_CORRECT;
   		$error=$ex_val;
	}
    }

		$i=0;
		foreach($extended_fields as $field)
		{
      $is_changeable_field = !($field->changeable == 0 && $is_siteUserEdit);
      $displayed = (($field->show_at_reg==1 && !$is_siteUserEdit) || ($field->show_at_edit==1 && $is_siteUserEdit));
			if( $field->published==1 && $is_changeable_field && $displayed )
			{
				switch($field->type)
				{
					case 'select':
					case 'radio':
					case 'text':
					case 'textarea':
						$value=mosGetParam($_POST, 'extend'.$field->id);
						break;
					case 'checkbox':
						$value=mosGetParam($_POST, 'extend'.$field->id, array() ,'array');
						$value=is_array($value) ? implode("\r\n", $value) : $value='';
						break;
					case 'date':
						$data['d']=mosGetParam($_POST, 'extend_d'.$field->id);
            $data['m']=mosGetParam($_POST, 'extend_m'.$field->id);
            $data['y']=mosGetParam($_POST, 'extend_y'.$field->id);
						if(!$data['y'] || !$data['m'] || !$data['d']){
							$value='';
						}else{
							$value=is_array($data) ? implode("-", $data) : $value='';
						}
						break;
					case 'file':
						$ufile=$_FILES['extend'.$field->id];
						$value=$ufile['name'];
						break;
					case 'simple phone':
						$phone['prefix']=mosGetParam($_POST, 'extend_prefix'.$field->id);
						$phone['phone']=mosGetParam($_POST, 'extend_phone'.$field->id);
						if(!$phone['prefix'] || !$phone['phone']){
							$value='';
						}else{
							$value=serialize($phone);
						}
						break;
          case 'phone':
   		      $phone['code']=mosGetParam($_POST, 'extend_code'.$field->id);
						$phone['prefix']=mosGetParam($_POST, 'extend_prefix'.$field->id);
						$phone['phone']=mosGetParam($_POST, 'extend_phone'.$field->id);
						$phone['extention']=mosGetParam($_POST, 'extend_extention'.$field->id);
						if(!$phone['code'] || !$phone['prefix'] || !$phone['phone']){
							$value='';
						}else{
							$value=serialize($phone);
						}
						break;
				}
				if($field->type=='file')
				{
					$query = "SELECT #__users_extended_data.*"
								."\n FROM #__users_extended_data"
								."\n WHERE user_id=".$my->id." and field_id = " . $field->id;
					$database->setQuery( $query );
					$field_data = $database->loadObjectList();
					$extended_fields[$i]->uvalue=$field_data[0]->uvalue;
				}
				else
				{
					$extended_fields[$i]->uvalue=$value;
				}

        $query = "SELECT count(#__users_extended_data.id)"
      			. "\n FROM #__users_extended_data"
      			. "\n WHERE `user_id` <> '".$userIdPosted."'"
            . "\n       AND `field_id` = ".$field->field_id
            . "\n       AND `uvalue` = '".$value."'";
    		$database->setQuery( $query );
	    	$unique_validation = $database->loadResult();
			
				if( $field->required==1 && $value=='' && $side!='admin')
				{
					if($field->type=='file' )
					{
						if( !mosGetParam($_POST, 'extend'.$field->id.'_hidden') )
						{
							$extended_fields[$i]->errormsg = MSG_IF_FIELD_IS_EMPTY;
							$error=true;
						}
					}
					else
					{
						$extended_fields[$i]->errormsg = MSG_IF_FIELD_IS_EMPTY;
						$error=true;
					}
				}
				else if( $field->validate && !preg_match($field->validate, $value))
				{
					if($side!='admin'){
						$extended_fields[$i]->errormsg = MSG_IF_FIELD_IS_NOT_VALID;
						$error=true;
					}
					else
					{
						$msg = 'Field "'.$field->title.'" enter incorectly: '. $value;
						mosRedirect( $path.$userIdPosted, $msg );
					}
				}
        else if( $field->unique_field == 1 && $unique_validation > 0 )
        {
          if($side!='admin'){
						$extended_fields[$i]->errormsg = MSG_IF_FIELD_IS_UNIQUE_ERROR;
						$error=true;
					}
        }

				if($value && $field->type=='file' && $side!='admin' && JEConfig::get('general.allowed_extends'))
				{
					$ex_val=true;
					foreach(explode("\n",str_replace("\r",'',JEConfig::get('general.allowed_extends'))) as $extend)
					{
						if(strtolower(str_replace('.','',strrchr($value,'.'))) == strtolower($extend))
						{

							$ex_val=false;

						}
					}
					if($ex_val) $extended_fields[$i]->errormsg = HEAD_MSG_IF_FILE_EXTEND_ISNOT_CORRECT;
					$error=$ex_val;
				}
			}
			$i++;
		}
		$error_standart_field = false;

    $is_not_valid_password = ( !$is_siteUserEdit && ( !mosGetParam($_REQUEST, 'verifyPass') || !mosGetParam($_REQUEST, 'password'))) || (mosGetParam($_REQUEST, 'password') != mosGetParam($_REQUEST, 'verifyPass'));
    if( !mosGetParam($_REQUEST, 'name') || !mosGetParam($_REQUEST, 'email') || !mosGetParam($_REQUEST, 'username') || $is_not_valid_password || !preg_match("/[0-9a-z_]+@[0-9a-z_^\.\-]+\.[a-z]{2,3}/i", mosGetParam($_REQUEST, 'email')))
		{
			$error_standart_field=true;
		}

		if(($error || $error_standart_field) && $side!='admin' )
		{
			userRegistrationAfterError($option, $my->id,$extended_fields,HEAD_MSG_IF_FIELD_IS_EMPTY,$task);
			return false;
		}
		return true;
	}

	function resizeImage($strSourceImagePath, $strDestImagePath, $intMaxWidth = 128, $intMaxHeight = 128)
    {
      $arrImageProps = getimagesize($strSourceImagePath);
      $intImgWidth   = $arrImageProps[0];
      $intImgHeight  = $arrImageProps[1];
      $intImgType    = $arrImageProps[2];
       
      switch( $intImgType) {
        case 1:
          $rscImg = ImageCreateFromGif($strSourceImagePath);
          break;
        case 2:
          $rscImg = ImageCreateFromJpeg($strSourceImagePath);
          break;
        case 3:
          $rscImg = ImageCreateFromPng($strSourceImagePath);
          break;
        default:
          return false;
      }
       
      if ( !$rscImg) return false;
       
      if ($intImgWidth > $intImgHeight) {
        $fltRatio = floatval($intMaxWidth / $intImgWidth);
      } else {
        $fltRatio = floatval($intMaxHeight / $intImgHeight);
      }
       
      $intNewWidth = intval($fltRatio * $intImgWidth);
      $intNewHeight = intval($fltRatio * $intImgHeight);
       
      $rscNewImg = imageCreateTrueColor($intNewWidth, $intNewHeight);
      if (!imageCopyResampled($rscNewImg, $rscImg, 0, 0,0, 0, $intNewWidth, $intNewHeight, $intImgWidth, $intImgHeight)){
        return false;
      }
       
      switch($intImgType) {
        case 1:
          $retVal = ImageGIF($rscNewImg, $strDestImagePath);
          break;
        case 3:
          $retVal = ImagePNG($rscNewImg, $strDestImagePath);
          break;
        case 2:
          $retVal = ImageJPEG($rscNewImg, $strDestImagePath, 90);
          break;
        default:
          return false;
      }
       
      ImageDestroy($rscNewImg);
       
      return true;
    }
	
	
	function saveUser_ext($userIdPosted='') //save new user or update if user already exist in DB
	{
		global $database,$mainframe, $my, $mosConfig_absolute_path;
		if(!$mainframe->isAdmin()){
		  if(!JUser::validateSaveUser('','front', mosGetParam($_POST, 'task'))){return ;}
		}

    if(!$userIdPosted)	$userIdPosted = mosGetParam($_POST, 'id');

		$query = "SELECT * FROM #__extending_field_list";
		$database->setQuery( $query );
		$extended_fields = $database->loadObjectList();

    if(JEConfig::get('general.enable_avatar') == 1) //save avatar if is option is turn on
    {
      $dir   = JEConfig::get('general.uploaded_avatar_directory');
      $point = opendir($dir);
      if(mosGetParam($_REQUEST,'remove_avatar','')=="remove") // delete user`s avatar if exist remove_avatar
      {
        while (($file = readdir($point)) !== false) {
      		if($file != '.' || $file != '..' || !is_dir($dir.DS.$file)){
      			if((substr_count( $file, 'user_'.$userIdPosted.'.' ) > 0)){
  		        unlink($dir.$file);
  		      }
      		}
      	}
      }
      
      $userfile = pathinfo($_FILES['field_core_avatar']['name']);
      $hidden_value = mosGetParam($_REQUEST,'field_core_avatar_hidden','');
	  //print $_FILES['field_core_avatar']['name']; exit;
      if($_FILES['field_core_avatar']['name']){ //delete existing avatar
        //if($my->id > 0 && !$mainframe->isAdmin()){
          while (($file = readdir($point)) !== false) {
            if($file != '.' || $file != '..' || !is_dir($dir.DS.$file)){
              if((substr_count( $file, 'user_'.$userIdPosted.'.' ) > 0)){
                unlink($dir.'/'.$file);
              }
            }
          }
          $database->setQuery("UPDATE `#__juser_users_additional_data` SET `avatar` = '' WHERE `user_id` = ".$userIdPosted);
          $database->query();
        //}
        
        
    		
         $userfile         = pathinfo($_FILES['field_core_avatar']['name']);
        $tmp_name         = $_FILES['field_core_avatar']['tmp_name'];
        $path_to_upload   = JEConfig::get('general.uploaded_avatar_directory');
        $extention        = strrchr( $userfile['basename'], '.' );
        $self_avatar_name = '/user_' . $userIdPosted
                            . strtolower(strrchr($_FILES['field_core_avatar']['name'],'.'));
        $tmp_resized_name = $mosConfig_absolute_path.'/cache'.$self_avatar_name;
        $end_avatar_name  = $path_to_upload.'/'.$self_avatar_name;
        //print $end_avatar_name; exit;
        JUser::resizeImage( $tmp_name, $tmp_resized_name,JEConfig::get('general.max_size'), JEConfig::get('general.max_size') );
        
        //echo "JFile::copy( $tmp_name, $new_file );";
        copy( $tmp_resized_name, $end_avatar_name );
        
        /*$tfile = $_FILES['field_core_avatar']['tmp_name'];
        $nfile = JEConfig::get('general.uploaded_avatar_directory')
                 . '/user_' . $userIdPosted
                 . strtolower(strrchr($_FILES['field_core_avatar']['name'],'.'));
        copy($tfile, $nfile);*/
        $value=$userfile['basename'];
		
		$value_p=$value;
		
	   	$query = "UPDATE `#__juser_users_additional_data` ".
	      			 "SET `mtime`= NOW(), `avatar` = '".$value_p."' ".
	      			 "WHERE user_id = ".$userIdPosted;
	   	$database->setQuery( $query );
	   	$database->query();
	   	if($database->getAffectedRows()<=0)
	   	{
	   		$query = "INSERT INTO `#__juser_users_additional_data`"
	               . "\n        (`user_id` ,`avatar`)"
	               . "\n values ('".$userIdPosted."','".$value_p."')";
	   		$database->setQuery( $query );
	   		$database->query();
	   	}
	   	$value_p='';
	   	$value = '';
		
		
      }
    }
    
    $is_siteUserEdit=(mosGetParam($_REQUEST, 'task')=='UserDetails' || mosGetParam($_REQUEST, 'task')=='saveUserEdit');
		foreach($extended_fields as $field)
		{
      $is_changeable_field = !($field->changeable == 0 && $is_siteUserEdit);
			if(		$field -> published==1
					&& ($is_changeable_field || $mainframe->isAdmin())
					&& (!(!$mainframe->isAdmin()
					&& (mosGetParam($_REQUEST, 'task')=='UserDetails'|| mosGetParam($_REQUEST, 'task')=='saveUserEdit') && $field->reg_only == 1)))
			{
				switch($field->type)
				{
					case 'select':
					case 'radio':
					case 'text':
						$value=htmlspecialchars(mosGetParam($_POST, 'extend'.$field->id),ENT_QUOTES);
						break;
					case 'checkbox':
						$value=mosGetParam($_POST, 'extend'.$field->id,'','array');
						$value=is_array($value)?implode("\r\n", $value) : $value='';
						break;
					case 'date':
						$data['d']=mosGetParam($_POST, 'extend_d'.$field->id);
						$data['m']=mosGetParam($_POST, 'extend_m'.$field->id);
            $data['y']=mosGetParam($_POST, 'extend_y'.$field->id);
						if(!$data['y'] || !$data['m'] || !$data['d']){
							$value='';
						}
						else{
							$value= is_array($data) ? implode("-", $data) : $value='';
						}
						break;
					case 'textarea':
						$value=htmlspecialchars($_POST['extend'.$field->id],ENT_QUOTES);
						break;
					case 'file':
						$userfile=pathinfo($_FILES['extend'.$field->id]['name']);
            $hidden_value = mosGetParam($_REQUEST,'extend'.$field->id.'_hidden','');
            if(!$userfile['basename'] && $hidden_value)
            {
              $value = $hidden_value;
              break;
            }
            else if(!$userfile['basename'] && !$hidden_value)
            {
              $value = '';
              break;
            }
            else{
  					  $exist_file='';
  					  $dir = JEConfig::get('general.uploaded_file_directory');
  					  $database->setQuery("SELECT `uvalue` FROM #__users_extended_data WHERE `user_id` = ".$userIdPosted." AND `field_id` = ".$field->id);
  					  $exist_file = $database->loadResult();
  					  if($exist_file){
  							$point = opendir($dir);
  							while (($file = readdir($point)) !== false) {
  								if($file != '.' && $file != '..' && !is_dir($dir.DS.$file) && $file == $exist_file){
  									unlink($dir.$exist_file);
  								}
  							}
  					  }

  						$tfile = $_FILES['extend'.$field->id]['tmp_name'];

  						$database->setQuery("SELECT `username` FROM `#__users` WHERE `id` = ". $userIdPosted);
  						$uname = $database->loadResult();
  						$user_part_name = substr(ereg_replace('[^a-zA-Z0-9]', '', $uname),0,15);
              if(!$user_part_name){
                $user_part_name = 'user_id'.$userIdPosted;
              }
              $field_part_name = substr(ereg_replace('[^a-zA-Z0-9]', '', $field->title),0,15);
              if(!$field_part_name){
                $user_part_name = 'field_id'.$field->id;
              }
              $new_name      = strtolower($user_part_name.'_'.$field_part_name.strrchr($userfile['basename'],'.'));
              $new_full_name = $dir.$new_name;

              copy($tfile, $new_full_name);
  						$value=$new_name;
            }
						break;
					case 'simple phone':
						$phone['prefix']=mosGetParam($_POST, 'extend_prefix'.$field->id);
						$phone['phone']=mosGetParam($_POST, 'extend_phone'.$field->id);
						if(!$phone['prefix'] || !$phone['phone']){
							$value='';
						}else{
							$value=serialize($phone);
						}
						break;
          case 'phone':
   		      $phone['code']=mosGetParam($_POST, 'extend_code'.$field->id);
						$phone['prefix']=mosGetParam($_POST, 'extend_prefix'.$field->id);
						$phone['phone']=mosGetParam($_POST, 'extend_phone'.$field->id);
						$phone['extention']=mosGetParam($_POST, 'extend_extention'.$field->id);
						if(!$phone['code'] || !$phone['prefix'] || !$phone['phone']){
							$value='';
						}else{
							$value=serialize($phone);
						}
						break;
				}
				$value_p=$value;
				$query = "UPDATE `#__users_extended_data` ".
							"SET `ctime`= NOW(), `uvalue` = '".$value_p."' ".
							"WHERE `field_id`= ".$field->id." and user_id = ".$userIdPosted;

				$database->setQuery( $query );
				$database->query();
				if($database->getAffectedRows()<=0)
				{
					$query = "insert INTO `#__users_extended_data` (`user_id`,`field_id` ,`uvalue`) values ('".$userIdPosted."','".$field->id."','".$value_p."')";
					$database->setQuery( $query );
					$database->query();
				}
			}
		}
	}

	function updateField($option) //Update changed field
	{
		global $database;
		if(mosGetParam($_POST, 'catid')==''){
			mosRedirect( 'index2.php?option=com_juser&task=editfield&field_id='.mosGetParam($_POST, 'field_id').'&hidemainmenu=1', 'Value "Category"  must be filled');
		}

		$database->setQuery("SELECT `ordering`, `catid` FROM `#__extending_field_list` WHERE `id` = ".mosGetParam($_POST, 'field_id'));
		$current_properties = $database->loadObjectList();
	 
		$validate_text = $_POST['validate'];
		
		if(!get_magic_quotes_gpc()){
		  str_replace('\\','\\\\',$validate_text);
		}
		
		$query = "update `#__extending_field_list` SET ".
			"`title`= '".mosGetParam($_POST, 'title')."', ".
			"`type`= '".mosGetParam($_POST, 'type')."', ".
			"`published`= '".mosGetParam($_POST, 'published')."', ".
			"`required`= '".mosGetParam($_POST, 'required')."', ".
			"`validate`= '".$validate_text."', ".
			"`size`= '".mosGetParam($_POST, 'size')."', ".
			"`size_vertical`= '".mosGetParam($_POST, 'size_vertical')."', ".
			"`count_cols`= '".mosGetParam($_POST, 'count_cols')."', ".
			"`changeable`= '".mosGetParam($_POST, 'changeable')."', ".
      "`unique_field`= '".mosGetParam($_POST, 'unique_field')."', ".
      "`search_by_this_field`= '".mosGetParam($_POST, 'search_by_this_field')."', ".
			"`show_at_reg`= '".mosGetParam($_POST, 'show_at_reg')."', ".
      "`show_at_edit`= '".mosGetParam($_POST, 'show_at_edit')."', ".
      "`display_at_users_list`= '".mosGetParam($_POST, 'display_at_users_list')."', ".
      "`access`= '".mosGetParam($_POST, 'access')."', ".
			"`description`= '".mosGetParam($_POST, 'description')."', ".
			"`catid`= '".mosGetParam($_POST, 'catid')."', ".
			"`uvalues`= '".mosGetParam($_POST, 'values')."', ".
			"`default_value`= '".mosGetParam($_POST, 'default_value')."' ".
			"where `id` = ".mosGetParam($_POST, 'field_id');
		$database->setQuery( $query );
		$database->query();

		/*save order*/
    $query = "UPDATE `#__extending_field_list` SET `ordering` = `ordering`+1 where `ordering` > ".mosGetParam($_POST, 'ordering','')." and `catid` = ".mosGetParam($_POST, 'catid');
		$database->setQuery( $query );
		$database->query();

    $query = "UPDATE `#__extending_field_list` SET `ordering` = ".(mosGetParam($_POST, 'ordering','')+1)." WHERE `id` = ".mosGetParam($_POST, 'field_id');
		$database->setQuery( $query );
		$database->query();

		$query = "UPDATE `#__extending_field_list` SET `ordering` = `ordering`-1 where `ordering` > ".$current_properties[0]->ordering." and `catid` = ".$current_properties[0]->catid;
		$database->setQuery( $query );
		$database->query();

		mosRedirect( 'index2.php?option='.$option.'&task=extend_fields', 'Field edited success');
	}

	function saveField($option) //Add new field in DB
	{
		global $database;
		if(mosGetParam($_POST, 'catid')==''){
			mosRedirect( 'index2.php?option=com_juser&task=new_field&hidemainmenu=1', 'Value "Category"  must be filled');
		}
		$query = "UPDATE `#__extending_field_list` SET `ordering` = `ordering`+1 where `ordering` > ".mosGetParam($_POST, 'ordering','')." and `catid` = ".mosGetParam($_POST, 'catid');
		$database->setQuery( $query );
		$database->query();

		$query = "INSERT INTO `#__extending_field_list` (`title`,`type`,`published`,`required`,`validate`,`size`,`size_vertical`,`description`, `changeable`,`unique_field`, `search_by_this_field`, `show_at_reg`,`show_at_edit`,`display_at_users_list`,`access`,`count_cols`,`catid`,`uvalues`,`ordering`,`default_value`) ".
			"values ( ".
			"'".mosGetParam($_POST, 'title')."', ".
			"'".mosGetParam($_POST, 'type')."', ".
			"'".mosGetParam($_POST, 'published')."', ".
			"'".mosGetParam($_POST, 'required')."', ".
			"'".$_POST['validate']."', ".
			"'".mosGetParam($_POST, 'size')."', ".
			"'".mosGetParam($_POST, 'size_vertical')."', ".
			"'".mosGetParam($_POST, 'description')."', ".
			"'".mosGetParam($_POST, 'changeable')."', ".
      "'".mosGetParam($_POST, 'unique_field')."', ".
      "'".mosGetParam($_POST, 'search_by_this_field')."', ".
			"'".mosGetParam($_POST, 'show_at_reg')."', ".
      "'".mosGetParam($_POST, 'show_at_edit')."', ".
      "'".mosGetParam($_POST, 'display_at_users_list')."', ".
      "'".mosGetParam($_POST, 'access')."', ".
			"'".mosGetParam($_POST, 'count_cols')."', ".
			"'".mosGetParam($_POST, 'catid')."', ".
			"'".mosGetParam($_POST, 'values')."', ".
			"'".(mosGetParam($_POST, 'ordering')+1)."', ".
			"'".mosGetParam($_POST, 'default_value')."')";
		$database->setQuery( $query );
		$database->query();

  	mosRedirect( 'index2.php?option='.$option.'&task=extend_fields', 'Field added success');
	}

	function deleteFields($cid=null, $option) //Delete field from DB
	{
		global $database;

		if ( is_array( $cid ) ) {
			if (count( $cid ) < 1) {
				mosRedirect( 'index2.php?option='. $option, 'Please select a field' );
			}

			foreach( $cid as $cidA ){
				$query = "SELECT * FROM #__extending_field_list WHERE `id` =".$cidA;
				$database->setQuery( $query );
				$field = $database->loadObjectList();
				if($field[0]->type == 'file')
				{
					$dir = JEConfig::get('general.uploaded_file_directory');
					$point = opendir($dir);
					 while (($file = readdir($point)) !== false) {
					 	 if($file != '.' || $file != '..' || !is_dir($dir.DS.$file))
					 	 {
					 	 	if(substr_count( $file, 'field_'.$field->id ) > 0 ) unlink($dir.$file);
					 	 }
					 }
				}
				$query = "DELETE FROM #__extending_field_list WHERE `id` =".$cidA;
				$database->setQuery( $query );
				$database->query();
				$query = "DELETE FROM #__users_extended_data WHERE `field_id` =".$cidA;
				$database->setQuery( $query );
				$database->query();
			}
			mosRedirect( 'index2.php?option='.$option.'&task=extend_fields', 'Fields deleted success');
		}
	}

	function publishFields( $cid=null, $option, $value) //Publishing selected fields
	{
		global $database;

		if ( is_array( $cid ) ) {
			if (count( $cid ) < 1) {
				mosRedirect( 'index2.php?option='. $option, 'Please select a field' );
			}
			foreach( $cid as $cidA ){
				$query = "update `#__extending_field_list` SET `published`= ".$value." where `id` = ".$cidA;
				$database->setQuery( $query );
				$database->query();
			}
			mosRedirect( 'index2.php?option='.$option.'&task=extend_fields', 'Fields hidden success');
		}
	}
	function create_standart_field($type, $field_title,$field_name, $field_value, $field_size, $field_description,$error,&$JavaScript)
	{
	  global $mainframe;
	  
	  $is_siteUserEdit=(mosGetParam($_REQUEST, 'task')=='UserDetails' || mosGetParam($_REQUEST, 'task')=='saveUserEdit');
	  
		$mark_color=JEConfig::get('general.required_color');
		if(!$mark_color) $mark_color="#dd5500";

		if(JEConfig::get('general.required_field')=='bold')
		{
			$title ='<b><font color="'.$mark_color.'">';
			$title.=$field_title;
			$title.='</font></b>';
		}
		else if(JEConfig::get('general.required_field')=='underline')
		{
			$title ='<u><font color="'.$mark_color.'">';
			$title.=$field_title;
			$title.='</font></u>';
		}

		else if(JEConfig::get('general.required_field')=='sign *')
		{
			$title =$field_title;
			$title.='<font color="'.$mark_color.'">*</font>';
		}
		else
		{
			$title =$field_title;
		}

		if(JEConfig::get('general.title_position')=='Over field')
		{
			$result ='<td nowrap="nowrap">'.$title;
		}
		else
		{
			$result ='<td width="130" valign="top" nowrap="nowrap">'.$title.'</td><td nowrap="nowrap">';
		}

		if(JEConfig::get('general.required_field')=="border")
		{
			$border_begin ='<div style="border-right:10px solid '.$mark_color.';border-bottom:1px solid '.$mark_color.'">';
			$border_end ='</div>';
		}
		else{$border_begin='';$border_end='';}

		$result.=$border_begin;
		if($error){$result.='<div style="color:#CC3300;font-weight:bolder;"><small id="error_'.$field_name.'">'.$error.'</small></div>';}
		else{$result.='<div style="color:#CC3300;font-weight:bolder;"><small id="error_'.$field_name.'"></small></div>';}
		if($field_name == 'username' && $is_siteUserEdit ){
		  $result.=$field_value;
		  $result.='<input type="hidden" name="'.$field_name.'" id="field_'.$field_name.'" class="inputbox" size="'.$field_size.'" value="'.$field_value.'" />';
		}
		else{
		  $result.='<input type="'.$type.'" name="'.$field_name.'" id="field_'.$field_name.'" class="inputbox" size="'.$field_size.'" value="'.$field_value.'" />';
		}
		$result.='<br><small align="left" class="small">'.$field_description.'</small>';
		$result.=$border_end;
		$result.='</td>';

		if(!$mainframe->isAdmin() && (mosgetparam($_REQUEST,'task') == 'UserRegistration' || (mosgetparam($_REQUEST,'task') != 'UserRegistration' && $field_name != 'password' && $field_name != 'verifyPass')))
		{
			$JavaScript['validate_standart_fields'].='if(document.getElementById("field_'.$field_name.'").value==""){
			document.getElementById("error_'.$field_name.'").innerHTML ="'.MSG_IF_FIELD_IS_EMPTY.'";
			err=true;
			}
			else{ document.getElementById("error_'.$field_name.'").innerHTML =""; }'."\n";
		}
		return $result;
	}
	function create_field($field,$error,&$JavaScript)
	{
		global $mainframe, $database, $mosConfig_live_site, $mosConfig_absolute_path;
    $is_siteUserEdit=(mosGetParam($_REQUEST, 'task')=='UserDetails' || mosGetParam($_REQUEST, 'task')=='saveUserEdit');
    
    if( !$field->published )
  	{return '';}

    
		if( !$mainframe->isAdmin() && (($is_siteUserEdit && $field->show_at_edit==0) || (!$is_siteUserEdit && $field->show_at_reg==0)) )
  	{return '';}


		$mark_color=JEConfig::get('general.required_color');
		if(!$mark_color){$mark_color="#dd5500";}

		if($field->required==1 && JEConfig::get('general.required_field')=="bold")
		{
			$title='<b><font color="'.$mark_color.'">';
			$title.=$field->title;
			$title.='</font></b>';
		}
		else if($field->required==1 && JEConfig::get('general.required_field')=="underline")
		{
			$title='<u><font color="'.$mark_color.'">';
			$title.=$field->title;
			$title.='</font></u>';
		}
		else
		{
			$title=$field->title;
		}

		if($field->required==1 && JEConfig::get('general.required_field')=="sign *")
		{
			$title.='<font color="'.$mark_color.'">*</font>';
		}

		if($field->required==1 && JEConfig::get('general.required_field')=="border")
		{
			$border_begin='<div style="border-right:10px solid '.$mark_color.';border-bottom:1px solid '.$mark_color.'">';
			$border_end='</div>';
		}
		else{ $border_begin='';$border_end=''; }

		if($field->default_value && $field->type != 'file' && $field->type != 'phone' && $field->type != 'date'){
		  if($mainframe->isAdmin())
		  {
		    if(mosGetParam($_REQUEST,'task','') == 'new')
		    {
		      $field->uvalue = $field->default_value;
		    }
		  }
		  else {
		    if(!$is_siteUserEdit)
		    {
		      $field->uvalue = $field->default_value;
		    }
		  }
		}

		if(JEConfig::get('general.title_position')=='Over field'){$result='<td>'.$title;}
		else{$result='<td width="130" valign="top" >'.$title.'</td><td >';}
		$result.=$border_begin;
		if(isset($field->errormsg)){$result.='<div style="color:#CC3300;font-weight:bolder;"><small id="error_extend'.$field->field_id.'" >'.$field->errormsg.'</small></div>';}
		else{$result.='<div style="color:#CC3300;font-weight:bolder;"><small id="error_extend'.$field->field_id.'" ></small></div>';}
		if(!isset($field->uvalue)){$field->uvalue='';}
		switch( $field->type )
		{
		  case 'simple phone':
       $phone = unserialize(stripslashes($field->uvalue));
       if( $is_siteUserEdit && $field->changeable==0 ){
          $result.=$phone[prefix].' '.$phone[phone];
       }
	     foreach($GLOBALS["country_phone_name"] as $country => $code)
       {
         $options[] = mosHTML::makeOption( $code, $country);
       }
       $result.= '<table><tr><td><small>'.ALL_AVATAR_PHONE_CITY_CODE.'</small><br>';
       $result.= ' <input maxlength="5" onkeyUp="formatInteger(\'field_extend_prefix'.$field->field_id.'\')" type="text" name="extend_prefix'.$field->field_id.'" id="field_extend_prefix'.$field->field_id.'" class="inputbox" size="5" value="'.$phone[prefix].'" />';
       $result.= '</td><td><small>'.ALL_AVATAR_PHONE_PHONE_NUMBER.'</small><br>';
       $result.= ' <input maxlength="10" onkeyUp="formatInteger(\'field_extend_phone'.$field->field_id.'\')" type="text" name="extend_phone'.$field->field_id.'" id="field_extend_phone'.$field->field_id.'" class="inputbox" size="10" value="'.$phone[phone].'"/>';
        /*JS validate*/
      	if($field->required==1 && !$mainframe->isAdmin)
				{
					$JavaScript['validate_extended_fields'].='if(
																document.getElementById("field_extend_prefix'.$field->field_id.'").value=="" ||
																document.getElementById("field_extend_phone'.$field->field_id.'").value==""){
					document.getElementById("error_extend'.$field->field_id.'").innerHTML ="'.MSG_IF_FIELD_IS_EMPTY.'";
					err=true;
					}
					else{ document.getElementById("error_extend'.$field->field_id.'").innerHTML =""; }'."\n";
				}
   			/*JS validate*/
       $result.='</td></tr></table>';
				break;
      case 'phone':

       $phone = unserialize(stripslashes($field->uvalue));
       if( $is_siteUserEdit && $field->changeable==0 ){
          $result.=$phone[code].' '.$phone[prefix].' '.$phone[phone].' '.$phone[extention];
       }
       $options[] = mosHTML::makeOption( '', '');
	     foreach($GLOBALS["country_phone_name"] as $country => $code)
       {
         $options[] = mosHTML::makeOption( $code, $country);
       }
       $result.='<table><tr><td nowrap="nowrap"><small>'.ALL_AVATAR_PHONE_COUNTRY_CODE.'</small><br>';
			 $result.= mosHTML::selectList( $options, 'extend_code'.$field->field_id, ' id="field_extend_code'.$field->field_id.'" ', 'value', 'text', $phone[code] );
			 
       $result.= '</td><td><small>'.ALL_AVATAR_PHONE_CITY_CODE.'</small><br>';
       $result.= ' <input maxlength="5" onkeyUp="formatInteger(\'field_extend_prefix'.$field->field_id.'\')" type="text" name="extend_prefix'.$field->field_id.'" id="field_extend_prefix'.$field->field_id.'" class="inputbox" size="5" value="'.$phone[prefix].'" />';
       $result.= '</td><td><small>'.ALL_AVATAR_PHONE_PHONE_NUMBER.'</small><br>';
       $result.= ' <input maxlength="10" onkeyUp="formatInteger(\'field_extend_phone'.$field->field_id.'\')" type="text" name="extend_phone'.$field->field_id.'" id="field_extend_phone'.$field->field_id.'" class="inputbox" size="10" value="'.$phone[phone].'"/>';
       $result.= '</td><td><small>'.ALL_AVATAR_PHONE_EXTENTION.'</small><br>';
       $result.= ' <input maxlength="5" onkeyUp="formatInteger(\'field_extend_extention'.$field->field_id.'\')" type="text" name="extend_extention'.$field->field_id.'" id="field_extend_extention'.$field->field_id.'" class="inputbox" size="5" value="'.$phone[extention].'"/>';
        /*JS validate*/
      	if($field->required==1 && !$mainframe->isAdmin)
				{
					$JavaScript['validate_extended_fields'].='if(
																document.getElementById("field_extend_code'.$field->field_id.'").value=="" ||
																document.getElementById("field_extend_prefix'.$field->field_id.'").value=="" ||
																document.getElementById("field_extend_phone'.$field->field_id.'").value==""){
					document.getElementById("error_extend'.$field->field_id.'").innerHTML ="'.MSG_IF_FIELD_IS_EMPTY.'";
					err=true;
					}
					else{ document.getElementById("error_extend'.$field->field_id.'").innerHTML =""; }'."\n";
				}
   			/*JS validate*/
       $result.='</td></tr></table>';
				break;
			case 'file':
			  $path           = stripslashes(JEConfig::get('general.uploaded_file_directory'));
        $path           = str_replace('\\','/',$path);
        $path=str_replace($mosConfig_absolute_path,$mosConfig_live_site,$path);
        $file_full_name = $path.$field->uvalue;

				if( $is_siteUserEdit && $field->changeable==0 ){
          $result.=$field->uvalue? MSG_FILE_EXIST.' <a target="_blank" href="'.$file_full_name.'"><img style="border:none" src="'.$mosConfig_live_site.'/administrator/images/filesave.png"></a><br>' : '';
        }
        else{
 					$path=stripslashes(JEConfig::get('general.uploaded_file_directory'));
 					$path=str_replace('\\','/',$path);
 					$path=str_replace($mosConfig_absolute_path,$mosConfig_live_site,$path);
 					$result.= $field->uvalue? MSG_FILE_EXIST.' <a target="_blank" href="'.$file_full_name.'"><img style="border:none" src="'.$mosConfig_live_site.'/administrator/images/filesave.png"></a><br>' : '';
   				$result.='	<input type="file" value="" name="extend'.$field->field_id.'" id="field_extend'.$field->field_id.'" class="inputbox" />';
   				$result.='	<input type="hidden" name="extend'.$field->field_id.'_hidden" id="field_extend'.$field->field_id.'_hidden" value="'.$field->uvalue.'" />';

   				/*JS validate*/
   				if($field->required==1 && !$mainframe->isAdmin)
   				{
   					$JavaScript['validate_extended_fields'].='if(document.getElementById("field_extend'.$field->field_id.'_hidden").value=="" && document.getElementById("field_extend'.$field->field_id.'").value==""){
   					document.getElementById("error_extend'.$field->field_id.'").innerHTML ="'.MSG_IF_FIELD_IS_EMPTY.'";
   					err=true;
   					}
   					else{ document.getElementById("error_extend'.$field->field_id.'").innerHTML =""; }'."\n";
   				}
   				/*JS validate*/
        }
				break;
			case 'separator':
				break;
			case 'text':
        if( $is_siteUserEdit && $field->changeable==0 ) $result.= $field->uvalue;
        else{
        		$value = $field->uvalue;

				  $result.='	<input type="text" name="extend'.$field->field_id.'" id="field_extend'.$field->field_id.'" class="inputbox" size="'.$field->size.'" value="'.$value.'" />';
          /*JS validate*/
   				if($field->required==1 && !$mainframe->isAdmin)
   				{
   					$JavaScript['validate_extended_fields'].='if(document.getElementById("field_extend'.$field->field_id.'").value==""){
   					document.getElementById("error_extend'.$field->field_id.'").innerHTML ="'.MSG_IF_FIELD_IS_EMPTY.'";
   					err=true;
   					}
   					else{ document.getElementById("error_extend'.$field->field_id.'").innerHTML =""; }'."\n";
   				}
				/*JS validate*/
        }
				break;
			case 'select':
        if( $is_siteUserEdit && $field->changeable==0 ) $result.= $field->uvalue;
        else{
          $options[] = mosHTML::makeOption( '', '' );

          foreach(explode("\r\n", $field->uvalues) as $option) $options[] = mosHTML::makeOption( $option, $option);

   				$result.= mosHTML::selectList( $options, 'extend'.$field->field_id, ' id="field_extend'.$field->field_id.'" ', 'value', 'text', $field->uvalue );

   				/*JS validate*/
   				if($field->required==1 && !$mainframe->isAdmin)
   				{
  	$JavaScript['validate_extended_fields'].='if(document.getElementById("field_extend'.$field->field_id.'").value==""){
   					document.getElementById("error_extend'.$field->field_id.'").innerHTML ="'.MSG_IF_FIELD_IS_EMPTY.'";
   					err=true;
   					}
   					else{ document.getElementById("error_extend'.$field->field_id.'").innerHTML =""; }'."\n";
   				}
   				/*JS validate*/
        }
				break;
			case 'checkbox':
        if( $is_siteUserEdit && $field->changeable==0 )
        {
           $values = explode("\n",str_replace("\r",'',$field->uvalue));
           foreach($values as $value) $result.='<div>'.$value.'</div>';
        }
        else
        {
   				$uvalues=explode("\n",str_replace("\r",'',$field->uvalues));
   				if($field->count_cols==0){ $count_cols=1;}
   				else{ $count_cols=$field->count_cols;}
   				$count_rows=round(count($uvalues)/$count_cols);
   				if($count_rows<count($uvalues)/$count_cols){$count_rows++;}
   				$curent_row=0;
   				unset($rows);
   				unset($condition);
   				$result.='<table><tr>';
   				$i=0;
   				foreach($uvalues as $value)
   				{
   					$i++;
   					$curent_row++;
   					if($curent_row>$count_rows){$curent_row=1;}
   					$kt=array_search ($value, explode("\n",str_replace("\r",'',$field->uvalue)));
   					if($kt || $kt===0)	{$checked='checked="checked"';}
   					else	{$checked='';}

   					$rows[$curent_row].='<td><input type="checkbox" id="field_extend'.$field->field_id.'['.$value.']" name="extend'.$field->field_id.'['.$value.']" class="inputbox" value="'.$value.'" '.$checked.' /> '.$value.'</td>';
   					$condition[$i].='document.getElementById("field_extend'.$field->field_id.'['.$value.']").checked ==true';
   				}
   				$result.=@implode("</tr><tr>",$rows);
   				$result.='</tr></table>';
   				/*JS validate*/
   				if($field->required==1 && !$mainframe->isAdmin)
   				{
   					$JavaScript['validate_extended_fields'].='
   					if('.@implode(" || ",$condition).'){
   					document.getElementById("error_extend'.$field->field_id.'").innerHTML ="";
   					}
   					else{ document.getElementById("error_extend'.$field->field_id.'").innerHTML ="'.MSG_IF_FIELD_IS_EMPTY.'";
   					err=true; }'."\n";
   				}
   				/*JS validate*/
        }
				break;
			case 'radio':
        if( $is_siteUserEdit && $field->changeable==0 ) $result.= $field->uvalue;
        else{
   				$uvalues=explode("\r\n", $field->uvalues);
   				if($field->count_cols==0){ $count_cols=1;}
   				else{ $count_cols=$field->count_cols;}
   				$count_rows=round(count($uvalues)/$count_cols);
   				if($count_rows<count($uvalues)/$count_cols){$count_rows++;}
   				$i=0;
   				$curent_row=0;
   				unset($rows);
   				unset($condition);
   				$result.='<table><tr>';
   				foreach(explode("\r\n", $field->uvalues) as $value)
   				{
   					$i++;
   					$curent_row++;
   					if($curent_row>$count_rows){$curent_row=1;}
   					if($field->uvalue==$value)	{$checked='checked="checked"';}
   					else	{$checked='';}
   					$rows[$curent_row].='<td><input type="radio" id="field_extend'.$field->field_id.'['.$value.']" name="extend'.$field->field_id.'" class="inputbox" value="'.$value.'" '.$checked.' /> '.$value.'</td>';
   					$condition[$i].='document.getElementById("field_extend'.$field->field_id.'['.$value.']").checked ==true';
   				}
   				$result.=@implode("</tr><tr>",$rows);
   				$result.='</tr></table>';
   				/*JS validate*/
   				if($field->required==1 && !$mainframe->isAdmin)
   				{
   					$JavaScript['validate_extended_fields'].='
   					if('.@implode(" || ",$condition).'){
   					document.getElementById("error_extend'.$field->field_id.'").innerHTML ="";
   					}
   					else{ document.getElementById("error_extend'.$field->field_id.'").innerHTML ="'.MSG_IF_FIELD_IS_EMPTY.'";
   					err=true; }'."\n";
   				}
   				/*JS validate*/
        }
				break;
			case 'textarea':
        if( $is_siteUserEdit && $field->changeable==0 ) $result.= $field->uvalue;
        else{
   				$result.='	<textarea id="field_extend'.$field->field_id.'" name="extend'.$field->field_id.'" wrap="virtual" cols="'.$field->size.'" rows="'.$field->size_vertical.'">'.$field->uvalue.'</TEXTAREA>';
   				/*JS validate*/
   				if($field->required==1 && !$mainframe->isAdmin)
   				{
   					$JavaScript['validate_extended_fields'].='if(document.getElementById("field_extend'.$field->field_id.'").value==""){
   					document.getElementById("error_extend'.$field->field_id.'").innerHTML ="'.MSG_IF_FIELD_IS_EMPTY.'";
   					err=true;
   					}
   					else{ document.getElementById("error_extend'.$field->field_id.'").innerHTML =""; }'."\n";
   				}
   				/*JS validate*/
        }
				break;
			case 'date':
			  $date_format = explode('-',JEConfig::get('general.date_format'));
        if( $is_siteUserEdit && $field->changeable==0 ){
          $value=explode("-", $field->uvalue);
          $date['DD'] = $value[0];
          $date['MM'] = $value[1];
          $date['YYYY'] = $value[2];
   				$result .= $date[$date_format[0]].' '.$date[$date_format[1]].' '.$date[$date_format[2]].' ';
        }
        else{
   				$options_d[] = mosHTML::makeOption( '', '');
   				for( $i=1;$i<=31;$i++ ){
   					$options_d[] = mosHTML::makeOption( $i, $i);
   				}
   				$options_m[] = mosHTML::makeOption( '',				'');
   				$options_m[] = mosHTML::makeOption( 'January',		ALL_MONTH_JANUARY);
   				$options_m[] = mosHTML::makeOption( 'February',		ALL_MONTH_FEBRUARY);
   				$options_m[] = mosHTML::makeOption( 'March',		ALL_MONTH_MARCH);
   				$options_m[] = mosHTML::makeOption( 'April',		ALL_MONTH_APRIL);
   				$options_m[] = mosHTML::makeOption( 'May',			ALL_MONTH_MAY);
   				$options_m[] = mosHTML::makeOption( 'June',			ALL_MONTH_JUNE);
   				$options_m[] = mosHTML::makeOption( 'July',			ALL_MONTH_JULY);
   				$options_m[] = mosHTML::makeOption( 'August',		ALL_MONTH_AUGUST);
   				$options_m[] = mosHTML::makeOption( 'September',	ALL_MONTH_SEPTEMBER);
   				$options_m[] = mosHTML::makeOption( 'October',		ALL_MONTH_OCTOBER);
   				$options_m[] = mosHTML::makeOption( 'November',		ALL_MONTH_NOVEMBER);
   				$options_m[] = mosHTML::makeOption( 'December',		ALL_MONTH_DECEMBER);

   				$data=getdate(time());

   				$options_y[] = mosHTML::makeOption( '', '');
   				for( $i=-50;$i<=80;$i++ ){
   					$options_y[] = mosHTML::makeOption( $data[year]-$i, $data[year]-$i);
   				}
   				if( $field->uvalue ){
   					$value=explode("-", $field->uvalue);
   					$data_y=$value[2];
   					$data_m=$value[1];
   					$data_d=$value[0];
   				}
   				else{
   					$data_y='';
   					$data_m='';
   					$data_d='';
   				}
   				foreach( $date_format as $date_elem){
     				switch($date_elem){
     				 case 'YYYY':
       				$result.= mosHTML::selectList( $options_y, 'extend_y'.$field->field_id, ' id="field_extend_y'.$field->field_id.'" ', 'value', 'text', $data_y );
       				break;
       			 case 'MM':
       				$result.= mosHTML::selectList( $options_m, 'extend_m'.$field->field_id, ' id="field_extend_m'.$field->field_id.'" ', 'value', 'text', $data_m );
       			  break;
       			 case 'DD':
       				$result.= mosHTML::selectList( $options_d, 'extend_d'.$field->field_id, ' id="field_extend_d'.$field->field_id.'" ', 'value', 'text', $data_d );
       			  break;
     				}
   				}
   				//$result.='<br><small align="left" class="small">'.$field->description.'</small>';
   				/*JS validate*/
   				if($field->required==1 && !$mainframe->isAdmin)
   				{
   					$JavaScript['validate_extended_fields'].='if(
   																document.getElementById("field_extend_y'.$field->field_id.'").value=="" ||
   																document.getElementById("field_extend_m'.$field->field_id.'").value=="" ||
   																document.getElementById("field_extend_d'.$field->field_id.'").value==""){
   					document.getElementById("error_extend'.$field->field_id.'").innerHTML ="'.MSG_IF_FIELD_IS_EMPTY.'";
   					err=true;
   					}
   					else{ document.getElementById("error_extend'.$field->field_id.'").innerHTML =""; }'."\n";
   				}
   				/*JS validate*/
        }
				break;
		}
		$result.=$field->description?'<br><small align="left" class="small">'.$field->description.'</small>':'';
		$result.=$border_end;
		$result.='</td>';
		return $result;
	}
  function create_core_avatar_field($type, $field_title, $field_value, $field_size, $error, &$JavaScript, $admin_id = NULL)
  {
    global $mainframe, $database, $my, $mosConfig_live_site,$mosConfig_absolute_path;
    $user_id=($admin_id===NULL ? $my->id : $admin_id);
    if(JEConfig::get('general.enable_avatar')==0)return; //if avatar disable do`t show him
    $is_siteUserEdit=(mosGetParam($_REQUEST, 'task')=='UserDetails' || mosGetParam($_REQUEST, 'task')=='saveUserEdit');
    if(isset($user_id) && $user_id > 0){
       $query = "SELECT *"
               ."\n FROM #__juser_users_additional_data"
               ."\n WHERE `user_id` = ".$user_id;
       $database->setQuery( $query );
       $avatar = $database->loadObjectList();
    }
    $mark_color=JEConfig::get('general.required_color');

		if(!$mark_color) $mark_color="#dd5500";

    if(JEConfig::get('general.required_avatar')==1)
    {
   		if(JEConfig::get('general.required_field')=='bold')
   		{
   			$title ='<b><font color="'.$mark_color.'">';
   			$title.=$field_title;
   			$title.='</font></b>';
   		}
   		else if(JEConfig::get('general.required_field')=='underline')
   		{
   			$title ='<u><font color="'.$mark_color.'">';
   			$title.=$field_title;
   			$title.='</font></u>';
   		}
   		else if(JEConfig::get('general.required_field')=='sign *')
   		{
   			$title =$field_title;
   			$title.='<font color="'.$mark_color.'">*</font>';
   		}
   		else { $title =$field_title;	}
    }
    else { $title =$field_title; }

		if(JEConfig::get('general.title_position')=='Over field')
		{
			$result ='<td nowrap="nowrap">'.$title;
		}
		else
		{
			$result ='<td width="130" valign="top" nowrap="nowrap">'.$title.'</td><td nowrap="nowrap">';
		}

		if(JEConfig::get('general.required_field')=="border" && JEConfig::get('general.required_avatar')==1)
		{
			$border_begin ='<div style="border-right:10px solid '.$mark_color.';border-bottom:1px solid '.$mark_color.'">';
			$border_end ='</div>';
		}
		else{$border_begin='';$border_end='';}

		$result.=$border_begin;
		if($error){
      $result.='<div style="color:#CC3300;font-weight:bolder;">'
                  .'<small id="error_field_core_avatar">'
                    .$error
                  .'</small>'
               .'</div>';
    }
		else{
      $result.='<div style="color:#CC3300;font-weight:bolder;">'
                .'<small id="error_field_core_avatar"></small>'
              .'</div>';
    }
    $path=stripslashes(JEConfig::get('general.uploaded_avatar_directory'));
    $path=str_replace('\\','/',$path);
    $path=str_replace($mosConfig_absolute_path,$mosConfig_live_site,$path);
    $result.=$avatar[0]->avatar? 'Already exist: <img  src="'.$path.'/user_'.$user_id.strtolower(strrchr($avatar[0]->avatar,'.')).'"><br>' : '';
		$result.='<input type="file" value="'.$field_value.'" name="field_core_avatar" id="field_core_avatar_" class="inputbox" />';
   	$result.='<input type="hidden" name="field_core_avatar_hidden" id="field_core_avatar_hidden_" value="'.$avatar[0]->avatar.'" />';
    if(JEConfig::get('general.required_avatar') == 0 && ($is_siteUserEdit || $mainframe->isAdmin())){
      $result.='<br>'.ALL_AVATAR_REMOVE.' <input type="checkbox" name="remove_avatar" value="remove">';
    }
		$result.='<br><small align="left" class="small">'.$field_description.'</small>';
		$result.=$border_end;
		$result.='</td>';

		if(JEConfig::get('general.required_avatar')==1 && !$mainframe->isAdmin())
		{
	    $JavaScript['validate_extended_fields'].='if(document.getElementById("field_core_avatar_hidden_").value=="" && document.getElementById("field_core_avatar_").value==""){
   		document.getElementById("error_field_core_avatar").innerHTML ="'.MSG_IF_FIELD_IS_EMPTY.'";
   		err=true;
   		}
   		else{ document.getElementById("error_field_core_avatar").innerHTML =""; }'."\n";
		}
		return $result;
  }
}
?>
